import React, { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Label } from "@/components/ui/label";
import { Settings as SettingsIcon, Key, CheckCircle, AlertCircle, ExternalLink } from "lucide-react";
import { useApiKey } from '@/contexts/ApiKeyContext';

const Settings: React.FC = () => {
  const { stratzApiKey, setStratzApiKey, hasValidApiKey } = useApiKey();
  const [tempApiKey, setTempApiKey] = useState(stratzApiKey);
  const [isSaving, setIsSaving] = useState(false);
  const [saveMessage, setSaveMessage] = useState<{ type: 'success' | 'error', message: string } | null>(null);

  const handleSave = async () => {
    setIsSaving(true);
    setSaveMessage(null);

    try {
      // 简单验证API key格式
      if (tempApiKey.trim() && !tempApiKey.includes('.')) {
        throw new Error('API key格式不正确，应该是JWT token格式');
      }

      setStratzApiKey(tempApiKey);
      setSaveMessage({ type: 'success', message: 'API key已保存成功！' });
    } catch (error) {
      setSaveMessage({ 
        type: 'error', 
        message: error instanceof Error ? error.message : '保存失败，请重试' 
      });
    } finally {
      setIsSaving(false);
      // 3秒后清除消息
      setTimeout(() => setSaveMessage(null), 3000);
    }
  };

  const handleReset = () => {
    setTempApiKey('');
    setSaveMessage(null);
  };

  const isChanged = tempApiKey !== stratzApiKey;

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-2">
        <SettingsIcon className="h-6 w-6" />
        <h1 className="text-2xl font-bold">设置</h1>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Key className="h-5 w-5" />
            STRATZ API 配置
          </CardTitle>
          <CardDescription>
            配置您的STRATZ API密钥以获取详细的比赛数据和统计信息
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="stratz-api-key">API Key</Label>
            <div className="flex gap-2">
              <Input
                id="stratz-api-key"
                type="password"
                placeholder="请输入您的STRATZ API key"
                value={tempApiKey}
                onChange={(e) => setTempApiKey(e.target.value)}
                className="flex-1"
              />
              <div className="flex items-center">
                {hasValidApiKey && !isChanged ? (
                  <Badge variant="default" className="bg-green-500">
                    <CheckCircle className="h-3 w-3 mr-1" />
                    已配置
                  </Badge>
                ) : tempApiKey.trim() && tempApiKey.includes('.') ? (
                  <Badge variant="secondary">
                    <AlertCircle className="h-3 w-3 mr-1" />
                    待保存
                  </Badge>
                ) : (
                  <Badge variant="outline">
                    <AlertCircle className="h-3 w-3 mr-1" />
                    未配置
                  </Badge>
                )}
              </div>
            </div>
          </div>

          <div className="flex gap-2">
            <Button 
              onClick={handleSave} 
              disabled={!isChanged || isSaving}
              className="flex-1"
            >
              {isSaving ? '保存中...' : '保存设置'}
            </Button>
            <Button 
              variant="outline" 
              onClick={handleReset}
              disabled={!tempApiKey.trim()}
            >
              清空
            </Button>
          </div>

          {saveMessage && (
            <Alert variant={saveMessage.type === 'error' ? 'destructive' : 'default'}>
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>{saveMessage.message}</AlertDescription>
            </Alert>
          )}

          <div className="pt-4 border-t">
            <h3 className="font-medium mb-2">如何获取STRATZ API Key？</h3>
            <div className="text-sm text-muted-foreground space-y-2">
              <p>1. 访问 <a href="https://stratz.com" target="_blank" rel="noopener noreferrer" className="text-primary hover:underline inline-flex items-center gap-1">STRATZ官网 <ExternalLink className="h-3 w-3" /></a></p>
              <p>2. 注册并登录您的账户</p>
              <p>3. 前往API设置页面申请API密钥</p>
              <p>4. 将获得的JWT token粘贴到上方输入框中</p>
            </div>
          </div>

          {!hasValidApiKey && (
            <Alert>
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>
                未配置API key时，部分功能可能无法正常使用。建议配置API key以获得完整体验。
              </AlertDescription>
            </Alert>
          )}
        </CardContent>
      </Card>
    </div>
  );
};

export default Settings;